import React, { useState, useEffect, FC, useRef } from 'react'
import {
  Row, Col, Card,
  Progress,
  Spin,
  Space,
  Modal,
  Table,
  Form,
  Select
} from 'antd'
import type { ColumnsType, ColumnType } from 'antd/es/table'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import XlModalFC from '@/components/xlmodal/xlmodal'
import { IData, IResponseCodeType, IStoreStatusModel } from '@/models/common'
import util from '@/utils/util'
import * as api from '@/api'
import { BaseOptionType } from 'antd/lib/select'
import "./storagepool.scss"

export interface IViewModel {
  disk_no_used: BaseOptionType[]
  pv_status: BaseOptionType[]
  lv_backup_status: BaseOptionType
  lv_status: BaseOptionType
  pageLoading: boolean
  /**
   * 添加镜像弹出框
   */
  addMirrorModalOpen: boolean
  /**
   * 添加镜像所需的两个磁盘
   */
  disk1: string
  disk2: string
  addDiskModalOpen: boolean
  /**
   * 添加磁盘名称
   */
  add_disk_name: string
  /**
   * 添加磁盘所属的镜像名称
   */
  add_raid_name: string
  notAuth: boolean
}
const StoragePool: FC = () => {

  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      disk_no_used: [],
      lv_backup_status: {
        disks: []
      },
      lv_status: {},
      pv_status: [],
      pageLoading: false,
      addMirrorModalOpen: false,
      disk1: "",
      disk2: "",
      addDiskModalOpen: false,
      add_disk_name: "",
      add_raid_name: "",
      notAuth: false
    }
  })

  useEffect(() => {
    
  }, [])

  const events = {
    onClickAddMirror() {
      const { ViewModel } = data
      ViewModel.addMirrorModalOpen = true
      setData({ ...data })
    },
    onDisk1Change(value: string) {
      const { ViewModel } = data
      ViewModel.disk1 = value
      setData({ ...data })
    },
    onDisk2Change(value: string) {
      const { ViewModel } = data
      ViewModel.disk2 = value
      setData({ ...data })
    },
    onAddMirrorCancel() {
      const { ViewModel } = data
      ViewModel.addMirrorModalOpen = false
      setData({ ...data })
    },
    onAddMirrorOk() {
      const { ViewModel } = data
      if (!ViewModel.disk1) {
        util.alertTip('请选择磁盘1')
        return
      }
      if (!ViewModel.disk2) {
        util.alertTip('请选择磁盘2')
        return
      }
      if (ViewModel.disk1 == ViewModel.disk2) {
        util.alertTip('磁盘1和磁盘2不能相同')
        return
      }
      methods.requestAddMirror()
    },
    onClickAddDisk(v: BaseOptionType) {
      const { ViewModel } = data
      ViewModel.addDiskModalOpen = true
      ViewModel.add_raid_name = v.name
      ViewModel.add_disk_name = ''
      setData({ ...data })
    },
    onDiskNameChange(value: string) {
      const { ViewModel } = data
      ViewModel.add_disk_name = value
      setData({ ...data })
    },
    onAddDiskCancel() {
      const { ViewModel } = data
      ViewModel.addDiskModalOpen = false
      setData({ ...data })
    },
    onAddDiskOk() {
      const { ViewModel } = data
      if (!ViewModel.add_disk_name) {
        util.alertTip('请选择磁盘')
        return
      }
      methods.requestAddDisk()
    },
    onClickAddBackupDisk() {
      const { ViewModel } = data
      const { lv_backup_status } = ViewModel
      ViewModel.addDiskModalOpen = true
      ViewModel.add_disk_name = ''
      ViewModel.add_raid_name = '/' + lv_backup_status.vg_name + "/" + lv_backup_status.lv_name
      setData({ ...data })
    },
    //删除磁盘
    onClickDeleteDisk(_: BaseOptionType, record: BaseOptionType, index: number) {
      const { pv_status } = data.ViewModel
      let obj = pv_status.find(o => o.disks.findIndex((v: any) => v.name == record.name) >= 0)
      if (obj && obj.name) {
        Modal.confirm({
          title: '删除',
          centered: true,
          closable: true,
          content: '确认删除该磁盘吗？',
          onOk() {
            return new Promise(async (resolve, reject) => {
              await methods.requestRemoveDisk(obj?.name, record.name)
              resolve(null)
            }).catch(() => console.log('Oops errors!'))
          },
          onCancel() {

          },
        })
      }
    },
  }

  const methods = {
    async requestStoreStatus() {
      const { ViewModel } = data
      ViewModel.pageLoading = true
      setData({ ...data })
      let res = await api.common.getStoreStatus<IStoreStatusModel>(null)
      const { code, data: StoreStatusData, message } = res
      if (code == IResponseCodeType.Success) {
        let { disk_no_used = [], pv_status = [], lv_backup_status, lv_status } = StoreStatusData
        ViewModel.disk_no_used = [...disk_no_used]
        ViewModel.pv_status = [...pv_status]
        ViewModel.lv_backup_status = lv_backup_status
        ViewModel.lv_status = lv_status
        ViewModel.disk1 = ''
        ViewModel.disk2 = ''
        ViewModel.add_disk_name = ''
        ViewModel.add_raid_name = ''
      } else if (code == IResponseCodeType.NotAuth) {
        ViewModel.notAuth = true
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    async requestRemoveDisk(raid_name: string, disk_name: string) {
      let res = await api.common.removeDisk<null>({
        raid_name,
        disk_name
      })
      const { code, message } = res
      util.alertTip(message)
      if (code == IResponseCodeType.Success) {
        methods.requestStoreStatus()
      }
    },
    async requestAddMirror() {
      let res = await api.common.addMirror<null>({
        disk1: data.ViewModel.disk1,
        disk2: data.ViewModel.disk2
      })
      const { code, message } = res
      util.alertTip(message)
      if (code == IResponseCodeType.Success) {
        events.onAddMirrorCancel()
        methods.requestStoreStatus()
      }
    },
    async requestAddDisk() {
      let res = await api.common.addDisk<null>({
        disk_name: data.ViewModel.add_disk_name,
        raid_name: data.ViewModel.add_raid_name
      })
      const { code, message } = res
      util.alertTip(message)
      if (code == IResponseCodeType.Success) {
        events.onAddDiskCancel()
        methods.requestStoreStatus()
      }
    },
    createStoragePoolColumns() {
      const columns: ColumnsType<BaseOptionType> = [
        {
          title: '类型',
          align: "left",
          key: 'type',
          dataIndex: 'type',
        },
        {
          title: '空间',
          align: "left",
          key: 'size',
          dataIndex: 'size',
        },
        {
          title: '状态',
          align: "left",
          key: 'health',
          dataIndex: 'health',
        },
        {
          title: '温度',
          align: "left",
          key: 'temperature',
          dataIndex: 'temperature',
        },
        {
          title: '操作',
          align: "center",
          key: 'action',
          render: (_, record, index) => (
            <Space size={4}>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickDeleteDisk(_, record, index)}>
                移除磁盘
              </XlButtonFC>
            </Space>
          ),
        }
      ]
      return columns
    },

    createBackupColumns() {
      const columns: ColumnsType<BaseOptionType> = [
        {
          title: '类型',
          align: "left",
          key: 'type',
          dataIndex: 'type',
        },
        {
          title: '空间',
          align: "left",
          key: 'size',
          dataIndex: 'size',
        },
        {
          title: '状态',
          align: "left",
          key: 'health',
          dataIndex: 'health',
        },
        {
          title: '温度',
          align: "left",
          key: 'temperature',
          dataIndex: 'temperature',
        },
      ]
      return columns
    },

    createDiskNoUsedColumns() {
      const columns: ColumnsType<BaseOptionType> = [
        {
          title: '名称',
          align: "left",
          key: 'name',
          dataIndex: 'name',
        },
        {
          title: '空间',
          align: "left",
          key: 'size',
          dataIndex: 'size',
        },
        {
          title: '状态',
          align: "left",
          key: 'health',
          dataIndex: 'health',
        },
        {
          title: '温度',
          align: "left",
          key: 'temperature',
          dataIndex: 'temperature',
        },
      ]
      return columns
    },

    renderStoragePoolTitle() {
      const { lv_status } = data.ViewModel
      return <Row className='card-title-box'>
        <Col>储存池（{lv_status.free}/{lv_status.size}）</Col>
        <Col className='progress'><Progress strokeLinecap="butt" percent={lv_status.percent} /></Col>
      </Row>
    },

    renderBackupTitle() {
      const { lv_backup_status } = data.ViewModel
      return <Row className='card-title-box'>
        <Col>备份盘（{lv_backup_status.free}/{lv_backup_status.size}）</Col>
        <Col className='progress'><Progress strokeLinecap="butt" percent={lv_backup_status.percent} /></Col>
      </Row>
    },

    renderDiskTitle(v: BaseOptionType) {
      return <Row className='card-title-box' gutter={16}>
        <Col className='title-name'>{v.name}</Col>
        <Col>同步：{v.sync_status}</Col>
        <Col>正常数：{v.active_devices}</Col>
        <Col>空间：{v.size}</Col>
      </Row>
    },

    renderOption(){
      return data.ViewModel.disk_no_used.map(o => {
        const text = o.name + '（' + o.size + '）'
        return <Select.Option value={o.name} key={o.name} label={text}>
          {text}
        </Select.Option>
      })
    },

    renderPage() {
      if (data.ViewModel.notAuth) {
        return null
      }
      return <>
        <Spin spinning={data.ViewModel.pageLoading}>
          <Card title='储存池'>
            <Row gutter={[0, 16]} className="storagepool-card-wrapper">
              <Col span={24}>
                <Card title={methods.renderStoragePoolTitle()} extra={<XlButtonFC type='primary' onClick={events.onClickAddMirror}>添加镜像</XlButtonFC>}>
                  <Row justify='space-between' className='disk-table-box' gutter={[16, 16]}>
                    {
                      data.ViewModel.pv_status.map(v => {
                        return <Col span={12} key={v.name}>
                          <Card title={methods.renderDiskTitle(v)} extra={<XlButtonFC type='primary' onClick={() => events.onClickAddDisk(v)}>添加磁盘</XlButtonFC>}>
                            <Table
                              rowKey='name'
                              bordered
                              pagination={false}
                              columns={methods.createStoragePoolColumns()}
                              dataSource={v.disks}
                            />
                          </Card>
                        </Col>
                      })
                    }
                  </Row>
                </Card>
              </Col>
              <Col span={24}>
                <Card title={methods.renderBackupTitle()} extra={<XlButtonFC type='primary' onClick={events.onClickAddBackupDisk}>添加磁盘</XlButtonFC>}>
                  <Table
                    rowKey='name'
                    bordered
                    pagination={false}
                    columns={methods.createBackupColumns()}
                    dataSource={data.ViewModel.lv_backup_status.disks}
                  />
                </Card>
              </Col>
              <Col span={24}>
                <Card title="未使用盘">
                  <Table
                    rowKey='name'
                    bordered
                    pagination={false}
                    columns={methods.createDiskNoUsedColumns()}
                    dataSource={data.ViewModel.disk_no_used}
                  />
                </Card>
              </Col>

            </Row>
          </Card>
        </Spin>
        {/* 添加镜像弹出框 */}
        <XlModalFC
          open={data.ViewModel.addMirrorModalOpen}
          onOk={events.onAddMirrorOk}
          onCancel={events.onAddMirrorCancel}
          title='添加镜像'
          destroyOnClose
        >
          <Form
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 17 }}
            autoComplete="off"
          >
            <Form.Item
              label="磁盘1"
              required
            >
              <Select placeholder='请选择磁盘1' allowClear value={data.ViewModel.disk1 || undefined} onChange={events.onDisk1Change} optionLabelProp="label">
                {
                  methods.renderOption()
                }
              </Select>
            </Form.Item>
            <Form.Item
              label="磁盘2"
              required
            >
              <Select placeholder='请选择磁盘2' allowClear value={data.ViewModel.disk2 || undefined} onChange={events.onDisk2Change} optionLabelProp="label">
                {
                  methods.renderOption()
                }
              </Select>
            </Form.Item>
          </Form>
        </XlModalFC>
        {/* 添加磁盘弹出框 */}
        <XlModalFC
          open={data.ViewModel.addDiskModalOpen}
          onOk={events.onAddDiskOk}
          onCancel={events.onAddDiskCancel}
          title='添加磁盘'
          destroyOnClose
        >
          <Form
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 17 }}
            autoComplete="off"
          >
            <Form.Item
              label="镜像"
              required
            >
              <Select disabled value={data.ViewModel.add_raid_name} showArrow={false}></Select>
            </Form.Item>
            <Form.Item
              label="磁盘"
              required
            >
              <Select placeholder='请选择磁盘' allowClear value={data.ViewModel.add_disk_name || undefined} onChange={events.onDiskNameChange} optionLabelProp="label">
                {
                  methods.renderOption()
                }
              </Select>
            </Form.Item>
          </Form>
        </XlModalFC>
      </>
    }
  }
  return methods.renderPage()
}
export default StoragePool
